package cn.gx.kevin.controller;

import cn.gx.kevin.common.utils.PagingResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import cn.gx.kevin.common.annotation.ApiDescript;
import cn.gx.kevin.common.annotation.ApiParams;
import cn.gx.kevin.common.annotation.ApiParamsDesc;
import cn.gx.kevin.common.annotation.ApiReturnDesc;
import cn.gx.kevin.common.ui.AjaxResult;
import cn.gx.kevin.common.ui.ClientButton;
import cn.gx.kevin.domain.User;
import cn.gx.kevin.domain.UserRole;
import cn.gx.kevin.service.*;
import cn.gx.kevin.controller.ResetfulBaseController;
import cn.gx.kevin.service.IBaseService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * Generate by Kevin's CodeBuilder
 **/
@ApiDescript("系统用户模块")
@Controller
@RequestMapping(value = "/user")
public class UserController extends ResetfulBaseController<User, String> {

    @Resource(name = "roleService")
    IRoleService roleService;

    @Resource(name = "userRoleService")
    IUserRoleService userRoleService;

    IUserService userService;

    @Resource(name = "orgService")
    IOrgService orgService;

    @Resource(name = "userService")
    @Override
    public void setService(IBaseService<User, String> service) {
        this.service = service;
        userService = (IUserService) service;
    }

    @Override
    @RequestMapping(value = "/page/{pageName}", method = RequestMethod.GET)
    public String page(@PathVariable("pageName") String pageName, HttpServletRequest request) throws Exception {
        return super.page(pageName, request);
    }

    /*
     * 页面 views/base/entityPath 文件夹路径
     * ***/
    @Override
    public String setPageModelPath(HttpServletRequest request) {
        // TODO Auto-generated method stub
        return "base" + File.separator + entityPath;
    }

    @Override
    protected void onRequestPage(String pageName, HttpServletRequest request) throws Exception {
        if ("form".equals(pageName) || "index".equals(pageName)) {
            JSONArray array = orgService.getOrgJsonByPid("0");
            request.setAttribute("orgJson", array);
        } else if ("role".equals(pageName)) {
            JSONArray rolesJson = roleService.getAvailabelRole();
            request.setAttribute("rolesJson", rolesJson);
            String userId = request.getParameter("userId");
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("userId", userId);
            request.setAttribute("userId", userId);
            List<UserRole> userRoles = userRoleService.selectParam(param);
            JSONArray array = JSONArray.parseArray(JSON.toJSONString(userRoles));
            request.setAttribute("userRoles", array);
        }
    }


    @ApiReturnDesc("{ code: '0正确/1异常',message: '信息',data: '数据对象'}")
    @ApiParamsDesc("{id:'id'}")
    @ApiDescript("根据ID查询数据")
    @ApiParams("{'id':''}")
    @Override
    @RequestMapping(value = "/get", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResult get(String id) throws Exception {
        return super.get(id);
    }

    @Override
    @ApiDescript("新增")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResult add(HttpServletRequest request) throws Exception {
        return super.add(request);
    }

    @ApiDescript("更新")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResult update(HttpServletRequest request) throws Exception {
        String id = request.getParameter("id");
        if ("0".equals(id)) {
            return returnFailData(getLang("user_opr_admin"));
        }
        return super.update(request);
    }

    @Override
    protected boolean loadDeleteDataForLog(HttpServletRequest request) {
        return true;
    }

    @ApiDescript("删除")
    @ApiParams("{'idList':'id1,id2'}")
    @RequestMapping(value = "/delete")
    public @ResponseBody
    AjaxResult delete(HttpServletRequest request) throws Exception {
        String idList = request.getParameter("idList");
        boolean isAdmin = false;
        if (idList.contains(",")) {
            String[] idTmpArr = idList.split(",");
            for (String id : idTmpArr) {
                if ("0".equals(id)) {
                    isAdmin = true;
                    break;
                }
            }
        } else {// 单条数据删除
            if ("0".equals(idList)) {
                isAdmin = true;
            }
        }
        if (isAdmin) {
            return returnFailData(getLang("user_opr_admin"));
        }
        return super.delete(request);
    }

    @ApiDescript("分页多条件可排序查询")
    @ApiParams("{'page':1,'pageSize':15,'_col_sort_fieldName':'asc','nameAccount':'','orgId':''}")
    @ApiParamsDesc("{page:'当前页',pageSize:'页大小',_col_sort_fieldName:'desc/asc，_col_sort_为前缀标志，fieldName为需要排序的字段名','nameAccount':'用户名/账号','orgId':'机构id'}")
    @RequestMapping(value = "/list")
    public @ResponseBody
    AjaxResult list(HttpServletRequest request) throws Exception {
        return super.list(request);
    }

    //查询出用户的配置的角色
    @Override
    protected void beforeListReturn(PagingResult<User> pgResult, HttpServletRequest request) {
         List<User> userList =   pgResult.getResultList();
         List<String> idList = new ArrayList<>();
         for(int i =0; i < userList.size(); i++){
             idList.add(userList.get(i).getId());
         }
         if(idList.size() > 0){
             Map<String,List<UserRole>> roleMap = null;
             try{
                 roleMap = this.userService.selectUserRole(idList);
             }catch (Exception x){
                 logger.error("",x);
             }
            if(roleMap != null){
                for(int i =0; i < userList.size(); i++){
                  User u =  userList.get(i);
                  String id = u.getId();
                  Object valueObj = roleMap.get(id);
                  List<UserRole> roles = new ArrayList<>();
                  if(valueObj != null){
                      roles = (List<UserRole>) valueObj;
                  }
                  StringBuilder builder = new StringBuilder();
                  if(roles != null && roles.size() > 0){
                      int j=0;
                      int len = roles.size();
                      for(UserRole r : roles){
                          builder.append(r.getRoleName());
                          if(j < len -1){
                              builder.append(",");
                          }
                          j++;
                      }
                  }else{
                      builder.append("-");
                  }
                  u.getExtFeildsMap().put("roles",builder.toString());
                }
            }
         }
    }

    @ApiDescript("非分页多条件/排序普通查询")
    @ApiParams("{'nameAccount':'','orgId':''}")
    @ApiParamsDesc("{'nameAccount':'用户名/账号','orgId':'机构id'}")
    @RequestMapping(value = "/query")
    public @ResponseBody
    AjaxResult query(HttpServletRequest request) throws Exception {
        return super.query(request);
    }

    @Override
    public Map<String, Object> setQueryParams(HttpServletRequest request) {
        try {
            return this.setListParams(request);
        } catch (Exception ex) {
            return null;
        }
    }

    @Override
    public LinkedHashMap<String, String> setOrderBy(HttpServletRequest request, String tablePrefix) {
        // TODO Auto-generated method stub
        LinkedHashMap<String, String> map = super.setOrderBy(request, "");
        if (!map.containsKey("org_id")) {
            map.put("org_id", "asc");
        }
        return map;
    }


    @ApiDescript("重置密码，不要求取得加密")
    @ApiParams("{'userId':'',newpwd:'','needOldpwd':'true/false','oldpwd':''}")
    @ApiParamsDesc("{'userId':'',newpwd:'新密码','needOldpwd':'是否需要验证旧密码','oldpwd':'旧密码'}")
    @RequestMapping(value = "/repasswd", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResult repasswd(HttpServletRequest request) throws Exception {
        String userId = request.getParameter("userId");
        String newpwd = request.getParameter("newpwd");
        String needOldpwd = request.getParameter("needOldpwd");
        if (StringUtils.isNotEmpty(needOldpwd) && "true".equals(needOldpwd)) {
            String oldPwd = request.getParameter("oldpwd");
            User user = this.service.get(userId);
            String _pwd = DigestUtils.md5Hex(oldPwd);
            if (!_pwd.equals(user.getUserPwd())) {
                return returnFailData(getLang("user_pwd_diff"));
            }
        }
        newpwd = DigestUtils.md5Hex(newpwd);
        if (userId.contains(";")) {
            this.userService.updatePwd(userId.split(";"), newpwd);
        } else {
            Map<String, Object> updatePrs = new HashMap<String, Object>();
            updatePrs.put("userPwd", newpwd);
            updatePrs.put("id", userId);
            this.service.updateParam(updatePrs);
        }
        return returnSuccData(null);
    }

    @ApiDescript("设置用户角色")
    @ApiParams("{'userId':'',roleIds:'id1,id2,id3'}")
    @ApiParamsDesc("{'userId':'用户id',roleIds:'角色id,逗号分割'}")
    @RequestMapping(value = "/roleUpdate", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResult roleUpdate(HttpServletRequest request) throws Exception {
        String userId = request.getParameter("userId");
        String roleIds = request.getParameter("roleIds");
        String[] roles = new String[]{};
        if (StringUtils.isNotEmpty(roleIds)) {
            roles = roleIds.split(",");
        }
        userRoleService.saveUserRole(userId, roles);
        return returnSuccData(null);
    }

    @Override
    protected Map<String, Object> setListParams(HttpServletRequest request) throws Exception {
        Map<String, Object> prs = new HashMap<String, Object>();
        String nameAccount = request.getParameter("keywords");
        String orgId = request.getParameter("orgId");

        if (StringUtils.isNotEmpty(nameAccount)) {
            prs.put("nameAccount", nameAccount);
        }
        if (StringUtils.isNotEmpty(orgId)) {
            prs.put("orgId", orgId);
        }
        return prs;
    }

    @Override
    public void buttonCreateHanlder(User bean, ClientButton button) {
        if (bean != null && bean.getId().equals("0") && !button.getHandler().equals("pwdFn")) {
            button.setDisabled(true);
        }
    }

    @Override
    public String saveFilter(User bean, boolean isupdate, HttpServletRequest request) {
        if (isupdate) {
            bean.setUserPwd(null);
        } else {
            String userPwd = bean.getUserPwd();
            String pwd = DigestUtils.md5Hex(userPwd);
            bean.setUserPwd(pwd);
        }
        return super.saveFilter(bean, isupdate, request);
    }

    @ApiReturnDesc("{ code: '0正确/1异常',message: '信息',data: '数据对象'}")
    @ApiParamsDesc("{id:'id','status':'1/0'}")
    @ApiDescript("禁用启用用户")
    @ApiParams("{id:'id','status':'1/0'}")
    @RequestMapping(value = "/status", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResult status(String id, Integer status) throws Exception {
        User user = new User();
        user.setId(id);
        user.setUserStatus(status);
        this.service.update(user);
        return returnSuccess();
    }

}
